package com.cml.handler;

import com.cml.MessageContext;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 姓名：陈茂林
 * 时间：2024/4/2
 * 描述：
 */
public class ServerDecoderHandler extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        Map receiveMessageContains = (Map) MessageContext.contains.get(channelHandlerContext.channel());
        if(receiveMessageContains == null){
            receiveMessageContains = new HashMap();
            MessageContext.contains.put(channelHandlerContext.channel(),receiveMessageContains);
        }
        Integer messageLength = (Integer) receiveMessageContains.get("length");
        Integer readMessageLength = (Integer) receiveMessageContains.get("readMessageLength");
        ByteBuf packageByteBufMessage = (ByteBuf) receiveMessageContains.get("packageByteBufMessage");
        if(messageLength ==null || messageLength.equals(readMessageLength) ){
            messageLength = byteBuf.readInt();
            receiveMessageContains.put("length",messageLength);
            readMessageLength=0;
            packageByteBufMessage= Unpooled.buffer(messageLength );
            receiveMessageContains.put("packageByteBufMessage",packageByteBufMessage);
        }

        Integer surplus = messageLength-readMessageLength;
        Integer nextReadNum = 0;
        if(surplus>=byteBuf.readableBytes()){
            nextReadNum = byteBuf.readableBytes();
        }else{
            nextReadNum=surplus;
        }
        byte[] message = new byte[nextReadNum];
        byteBuf.readBytes(message);
        packageByteBufMessage.writeBytes(message);


        receiveMessageContains.put("readMessageLength",readMessageLength+nextReadNum);
        if(messageLength.equals(readMessageLength+nextReadNum) ){
            byte[] bb = new byte[packageByteBufMessage.readableBytes()];
            packageByteBufMessage.readBytes(bb);
            list.add(new String(bb));
            MessageContext.contains.remove(channelHandlerContext.channel());
        }else{
            return;
        }
    }
}
